package com.px.common.core;


import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NonNull;
import org.springframework.dao.DuplicateKeyException;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


@Getter
@AllArgsConstructor(access = AccessLevel.PRIVATE)
public class Response<T> {
    private boolean success;
    private int status;
    private String message;
    private T data;

    public static <T> Response<T> success(T data) {
        return new Response<>(true, RespCode.SUCCESS.getStatus(), RespCode.SUCCESS.getMsg(), data);
    }

    public static <T> Response<T> success(@NonNull RespCode respCode, T data) {
        return new Response<>(true, respCode.getStatus(), respCode.getMsg(), data);
    }

    public static <T> Response<T> fail(RespCode respCode, T data) {
        return new Response<>(false, respCode.getStatus(), respCode.getMsg(), data);
    }

    public static <T> Response<T> fail(@NonNull RespException ex) {
        return new Response<>(false, ex.getStatus(), ex.getMessage(), null);
    }

    public static <T> Response<T> fail(@NonNull RuntimeException ex) {
        return new Response<>(false, RespCode.PARA_ERROR.getStatus(), ex.getMessage(), null);
    }

    static Pattern usedFieldReg = Pattern.compile("'.*?'");
    public static Response<String> fail(@NonNull DuplicateKeyException ex) {
        Matcher m = usedFieldReg.matcher(ex.getCause().getMessage());
        if (m.find()){
            String msg = m.group(0) + " 不能重复";
            return fail(RespCode.FIELD_USED, msg);
        }
        return fail(RespCode.FIELD_USED, ex.getCause().getMessage());
    }
}